package mysqldb

import (
	"database/sql"
	"fmt"
	"github.com/gogf/gf/g/os/glog"
	"github.com/spf13/viper"
	"log"
	"time"
	"usertodo/pkg/bootstrap"
)

var (
	XQXTDB *sql.DB
	BUZDB  *sql.DB
)

// mysqlconfg: 存储MySQL配置结构体
type mysqlconfg struct {
	dbname string
	dbuser string
	dbpwd  string
	dbhost string
	dbport string
}

// connent2MySQL: 连接MySQL
func connent2MySQL(dsn string) (db *sql.DB) {
	db, err := sql.Open("mysql", dsn)
	err = db.Ping()
	if err != nil {
		glog.Panic("连接MySQL失败" + err.Error())
		return
	}
	db.SetMaxIdleConns(2)
	db.SetMaxOpenConns(10)
	db.SetConnMaxLifetime(30 * time.Second)
	return
}

// getdb_list: 从配置文件中->获取MySQL配置列表
func getdb_list() map[string]string {
	var dbs = make(map[string]string)

	// 连接示例:
	// 	"user:password@tcp(192.168.1.28:3306)/dbname?charset=utf8mb4,utf8&tls=skip-verify",

	for db, _ := range viper.GetStringMap("mysql") {
		m := mysqlconfg{}
		m.dbname = viper.GetString("mysql." + db + ".dbname")
		m.dbhost = viper.GetString("mysql." + db + ".dbhost")
		m.dbport = viper.GetString("mysql." + db + ".dbport")
		m.dbuser = viper.GetString("mysql." + db + ".dbuser")
		m.dbpwd = viper.GetString("mysql." + db + ".dbpwd")
		//  fmt.Println(m)
		dbs[db] = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8",
			m.dbuser,
			m.dbpwd,
			m.dbhost,
			m.dbport,
			m.dbname,
		)
	}
	return dbs
}

type MySQLDB struct {
	bootstrap.BaseStarter
}

func (m *MySQLDB) Setup(ctx bootstrap.StarterContext) {
	time.Sleep(time.Millisecond*50)
	// 获取MySQL配置列表
	// var dblist = getdb_list()
	for db, dsn := range getdb_list() {
		switch db {
		case "xqxt":
			XQXTDB = connent2MySQL(dsn)
		case "buz":
			BUZDB = connent2MySQL(dsn)
		default:
			log.Panic(db + "未知数据库类型")
		}
	}
}
func (m *MySQLDB) StartBlocking() bool {
	return true
}
